package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.OrderShipping;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 *  cskaoyan
 */
@Slf4j
@Component
@Service
public class OrderQueryServiceImpl implements OrderQueryService {


    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;

    @Override
    public OrderListResponse getOrderList(OrderListRequest orderListRequest) {
        OrderListResponse orderListResponse = new OrderListResponse();
        try {
            //pagehelper 去分页
            Integer page = orderListRequest.getPage();
            Integer size = orderListRequest.getSize();

//            String sort = orderListRequest.getSort();

            //选出order表的信息，orderItem，和orderShip的信息，
            //这里比较繁琐的怎么去封装的问题，类有很多，不知道装到哪里去
            PageHelper.startPage(page, size);

            Example example = new Example(Order.class);
            example.createCriteria()
                    .andEqualTo("userId",orderListRequest.getUserId());
//            example.orderBy(sort);

            List<Order> orders = orderMapper.selectByExample(example);

            PageInfo<Order> pageInfo = new PageInfo<>(orders);
            long total = pageInfo.getTotal();

            List<OrderDetailInfo> orderDetailInfos = orderConverter.order2detailList(orders);

            for (OrderDetailInfo orderDetailInfo : orderDetailInfos) {
                String orderId = orderDetailInfo.getOrderId();
                //根据orderId 选 orderItems
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
                orderDetailInfo.setOrderItemDto(orderItemDtos);

                //根据orderId 选 shipping信息
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);
            }

            orderListResponse.setData(orderDetailInfos);
            orderListResponse.setTotal(total);
            orderListResponse.setCode(OrderRetCode.SUCCESS.getCode());
            orderListResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("OrderQueryServiceImpl.getOrderList occur Exception: "+ e);
            ExceptionProcessorUtils.wrapperHandlerException(orderListResponse,e);
        }

        return orderListResponse;
    }

    @Override
    public OrderDetailResponse getOrderDetail(OrderDetailRequest orderDetailRequest) {
        OrderDetailResponse orderDetailResponse = new OrderDetailResponse();
        OrderDetailDto orderDetailDto = new OrderDetailDto();

        try{
            //根据orderId 获取订单
            String orderId = orderDetailRequest.getOrderId();
            Long userId = orderDetailRequest.getUserId();

            orderDetailDto.setUserId(userId);

            Order order = orderMapper.selectByPrimaryKey(orderId);

            //设置金额
            orderDetailDto.setOrderTotal(order.getPayment());
            orderDetailDto.setOrderStatus(order.getStatus());

            Example example = new Example(OrderItem.class);
            example.createCriteria()
                    .andEqualTo("orderId",orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

            List<OrderItemWithStatusDto> orderItemWithStatusDtos = orderConverter.item2dtoStatus(orderItems);

            //设置商品
            orderDetailDto.setGoodsList(orderItemWithStatusDtos);

            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);

            for (OrderItemWithStatusDto orderItemWithStatusDto : orderItemWithStatusDtos) {

            }

            orderDetailDto.setStreetName(orderShipping.getReceiverAddress());
            orderDetailDto.setTel(orderShipping.getReceiverMobile());
            orderDetailDto.setUserName(orderShipping.getReceiverName());

            orderDetailResponse.setOrderDetailDto(orderDetailDto);
            orderDetailResponse.setCode(OrderRetCode.SUCCESS.getCode());
            orderDetailResponse.setMsg(OrderRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("OrderQueryServiceImpl.getOrderDetail occur Exception: "+ e);
            ExceptionProcessorUtils.wrapperHandlerException(orderDetailResponse,e);
        }

        return orderDetailResponse;
    }

    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest deleteOrderRequest) {
        DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
        String orderId = deleteOrderRequest.getOrderId();
        try{
            try {
                //删除order表
                int orderResult = orderMapper.deleteByPrimaryKey(orderId);
                //删除order_item表
                Example example = new Example(OrderItem.class);
                example.createCriteria()
                        .andEqualTo("orderId", orderId);
                int orderItemResult = orderItemMapper.deleteByExample(example);
                //删除order_shipping表
                Example exampleShipping = new Example(OrderShipping.class);
                exampleShipping.createCriteria()
                        .andEqualTo("orderId", orderId);
                int orderShippingResult = orderShippingMapper.deleteByExample(example);
                deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
                deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
            }catch (Exception e){
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
            }

        }catch (Exception e){
            log.error("OrderQueryServiceImpl.deleteOrder occur Exception: "+ e);
            ExceptionProcessorUtils.wrapperHandlerException(deleteOrderResponse,e);
        }

        return deleteOrderResponse;
    }

    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) {
        CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
        String orderId = cancelOrderRequest.getOrderId();

        try{
            //更新订单表，状态
            try {
                Order order = new Order();
                order.setUpdateTime(new Date());
                order.setStatus(5);
                order.setCloseTime(new Date());
                order.setOrderId(orderId);
                int i = orderMapper.updateByPrimaryKeySelective(order);
                //更新订单商品表 状态 同时更新库存表
                Example example = new Example(OrderItem.class);
                example.createCriteria()
                        .andEqualTo("orderId", orderId);
                List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
                for (OrderItem orderItem : orderItems) {
                    Long itemId = orderItem.getItemId();
                    Integer num = orderItem.getNum();

                    Stock stock = new Stock();
                    stock.setItemId(itemId);
                    stock.setStockCount(Long.valueOf(num));
                    stock.setLockCount(-num);

                    int i1 = stockMapper.updateByPrimaryKeySelective(stock);
                }

                OrderItem orderItem = new OrderItem();
                orderItem.setStatus(2);
                orderItemMapper.updateByExampleSelective(orderItem, example);

                //更新订单物流表,物流表没有状态码，就放着就好了，因为订单还是可以显示的
                cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
                cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
            }catch (Exception e){
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
            }
        }catch (Exception e){
            log.error("OrderQueryServiceImpl.cancelOrder occur Exception: "+ e);
            ExceptionProcessorUtils.wrapperHandlerException(cancelOrderResponse,e);
        }
        return cancelOrderResponse;
    }
}
